package com.company.indicationshots.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.company.indicationshots.R;
import com.company.indicationshots.database.DatabaseHelper;
import com.company.indicationshots.model.Score;
import com.company.indicationshots.model.ShotExcelData;
import com.company.indicationshots.view.RecordCoordinateSystemView;
import com.company.indicationshots.view.StrokeTextView;
import com.company.indicationshots.view.PreShotTargetResultView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.date.DateUtil;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
//射靶历史记录页面
public class SmartIntegrateTargetActivity extends AppCompatActivity {

    SimpleAdapter recordAdapter;
    DatabaseHelper dbHelper;
    SQLiteDatabase db;
    PreShotTargetResultView targetResultView = new PreShotTargetResultView();
    ListView recordScoreList;
    ImageView recordTarget;
    RecordCoordinateSystemView recordListChart;
    ImageView gunTypePic;
    StrokeTextView gunTypeView;
    TextView sumView;
    TextView missView;
    TextView highestView;
    TextView avgView;
    TextView varianceView;
    int clickedPosition;
    List<Map<String, Object>> recordScoreDataList;
    SimpleAdapter recordScoreAdapter;
    PopupWindow popupWindow;
    File mUdiskRoot;
    int id;
    ImageView udisk;

    @SuppressLint({"Range", "MissingInflatedId"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_smart_integrate_target);


        View recordWhole = findViewById(R.id.record_whole);
        gunTypeView = findViewById(R.id.record_gun_type);
        sumView = findViewById(R.id.record_sum);
        missView = findViewById(R.id.record_miss);
        highestView = findViewById(R.id.record_highest);
        avgView = findViewById(R.id.record_avg);
        varianceView = findViewById(R.id.record_variance);
        ImageView back = findViewById(R.id.back);
        recordTarget = findViewById(R.id.record_target);
        ImageView export = findViewById(R.id.export);
        udisk = findViewById(R.id.udisk);

        //enter跳转
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回到主界面
                finish();
            }
        });

        mUdiskRoot = new File(com.lztek.toolkit.Lztek.create(SmartIntegrateTargetActivity.this).getUsbStoragePath());

        export.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mUdiskRoot.exists() || !mUdiskRoot.isDirectory()) {
                    Toast.makeText(SmartIntegrateTargetActivity.this, "未发现U盘,导出射靶成绩单失败", Toast.LENGTH_SHORT).show();
                    return;
                }
                createExcel(mUdiskRoot);
            }
        });

        ListView recordList = findViewById(R.id.record_list);

        dbHelper = new DatabaseHelper(this);
        // 获取可写数据库实例
        db = dbHelper.getWritableDatabase();

        //查询射靶历史数据
        List<Map<String, Object>> recordDataList = new ArrayList<>();
        Map<String, Object> map = null;
        String sql = "select id,shooter,gun_type,sum,miss,highest,avg,variance,create_time from record order by id desc";
        Cursor cursor = db.rawQuery(sql, null);
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String shooter = cursor.getString(cursor.getColumnIndex("shooter"));
            String gunType = cursor.getString(cursor.getColumnIndex("gun_type"));
            int sum = cursor.getInt(cursor.getColumnIndex("sum"));
            int miss = cursor.getInt(cursor.getColumnIndex("miss"));
            float highest = cursor.getFloat(cursor.getColumnIndex("highest"));
            float avg = cursor.getFloat(cursor.getColumnIndex("avg"));
            float variance = cursor.getFloat(cursor.getColumnIndex("variance"));
            String createTime = cursor.getString(cursor.getColumnIndex("create_time"));
            map = new HashMap<>();
            map.put("id", id);
            map.put("record_shooter", shooter);
            map.put("gunType", gunType);
            map.put("sum", sum);
            map.put("miss", miss);
            map.put("highest", highest);
            map.put("avg", avg);
            map.put("variance", variance);
            map.put("record_createTime", createTime);
            recordDataList.add(map);
        }
        cursor.close();

        String[] from = {"record_shooter", "record_createTime"};
        int[] to = {R.id.record_shooter, R.id.record_createTime};

        recordScoreList = findViewById(R.id.record_score_list);
        recordListChart = findViewById(R.id.record_list_chart);
        gunTypePic = findViewById(R.id.gun_type_pic);
        SparseBooleanArray selectedItems = new SparseBooleanArray();

        //创建适配器把数据装配到射靶历史记录列表
        recordAdapter = new SimpleAdapter(this, recordDataList, R.layout.record_list_item, from, to) {

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {

                View view = super.getView(position, convertView, parent);

                // 设置当前行的背景颜色
                view.setBackgroundColor(selectedItems.get(position, false) ? Color.parseColor("#0e932e") : Color.BLACK);

                // 设置点击监听器
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        // 清除所有选中状态
                        selectedItems.clear();

                        // 设置当前行为选中状态
                        clickedPosition = (Integer) v.getTag();
                        selectedItems.put(clickedPosition, true);

                        // 刷新当前行的视图背景颜色
                        notifyDataSetChanged();

                        Map<String, Object> record = (Map<String, Object>) getItem(position);
                        id = (int) record.get("id");

                        //查询历史成绩数据
                        recordScoreDataList = new ArrayList<>();
                        Map<String, Object> map = null;
                        String sql = "select num,ring,distance,x,y,time from score where ring >= 5 and record_id = ?";
                        String[] args = new String[]{String.valueOf(id)};
                        Cursor cursor = db.rawQuery(sql, args);
                        while (cursor.moveToNext()) {
                            int num = cursor.getInt(cursor.getColumnIndex("num"));
                            float ring = cursor.getFloat(cursor.getColumnIndex("ring"));
                            String distance = cursor.getString(cursor.getColumnIndex("distance"));
                            float x = cursor.getFloat(cursor.getColumnIndex("x"));
                            float y = cursor.getFloat(cursor.getColumnIndex("y"));
                            float time = cursor.getFloat(cursor.getColumnIndex("time"));
                            map = new HashMap<>();
                            map.put("record_num", num);
                            map.put("record_ring", ring);
                            map.put("record_distance", distance);
                            map.put("x", x);
                            map.put("y", y);
                            map.put("record_time", time);
                            recordScoreDataList.add(map);
                        }
                        cursor.close();

                        String[] from = {"record_num", "record_ring", "record_distance", "record_time"};
                        int[] to = {R.id.record_num, R.id.record_ring, R.id.record_distance, R.id.record_time};

                        //创建适配器把数据装配到射靶历史成绩列表
                        recordScoreAdapter = new SimpleAdapter(SmartIntegrateTargetActivity.this, recordScoreDataList, R.layout.record_score_list_item, from, to) {
                            //初始时没有选中的行
                            int selectedPosition = 0;

                            @Override
                            public View getView(int position, View convertView, ViewGroup parent) {
                                View view = super.getView(position, convertView, parent);
                                //默认首行选中并设置行的背景颜色
                                if (selectedPosition == position) {
                                    //选中行背景颜色为绿色
                                    view.setBackgroundColor(Color.parseColor("#0e932e"));
                                } else {
                                    //其他为默认色
                                    view.setBackgroundColor(Color.BLACK);
                                }

                                view.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        //点击行设置选中
                                        selectedPosition = position;
                                        notifyDataSetChanged();

                                        //靶高亮显示该成绩
                                        Map<String, Object> selectScoreMap = (Map<String, Object>) getItem(position);
                                        targetResultView.getTargetView(SmartIntegrateTargetActivity.this, recordScoreDataList, selectScoreMap, recordTarget);
                                    }
                                });

                                return view;
                            }
                        };

                        //将recordScoreAdapter设置到recordScoreList
                        recordScoreList.setAdapter(recordScoreAdapter);

                        //胸环靶
                        Map<String, Object> firstScoreMap = (Map<String, Object>) recordScoreAdapter.getItem(0);
                        targetResultView.getTargetView(SmartIntegrateTargetActivity.this, recordScoreDataList, firstScoreMap, recordTarget);

                        //坐标系
                        List<Score> coordList = new ArrayList<>();
                        Score score = null;
                        sql = "select num,ring,distance,x,y,time from score where record_id = ?";
                        args = new String[]{String.valueOf(id)};
                        cursor = db.rawQuery(sql, args);
                        while (cursor.moveToNext()) {
                            int num = cursor.getInt(cursor.getColumnIndex("num"));
                            float ring = cursor.getFloat(cursor.getColumnIndex("ring"));
                            score = new Score(num, ring, null, null, 0, 0, 0);
                            coordList.add(score);
                        }
                        cursor.close();

                        recordListChart.setData(coordList.size(), coordList);

                        //枪型和计算数据
                        String gunType = (String) record.get("gunType");
                        String sum = "总发数 : " + (int) record.get("sum");
                        String miss = "脱靶 : " + (int) record.get("miss");
                        String highest = "最高环数 : " + (float) record.get("highest");
                        String avg = "平均环数 : " + (float) record.get("avg");
                        String variance = "方差 : " + (float) record.get("variance");

                        if (gunType.equals("95式自动步枪")) {
                            gunTypePic.setImageResource(R.drawable.rifle);
                        } else {
                            gunTypePic.setImageResource(R.drawable.pistol);
                        }
                        gunTypeView.setText(gunType + " 胸环靶");
                        sumView.setText(sum);
                        missView.setText(miss);
                        highestView.setText(highest);
                        avgView.setText(avg);
                        varianceView.setText(variance);
                    }
                });
                // 设置tag，以便在onClick中知道点击的是哪一行
                view.setTag(position);

                //长按射靶历史记录单条
                view.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        // 加载菜单布局
                        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        View popupView = inflater.inflate(R.layout.record_menu, null);

                        // 创建PopupWindow实例
                        popupWindow = new PopupWindow(popupView,
                                WindowManager.LayoutParams.WRAP_CONTENT,
                                WindowManager.LayoutParams.WRAP_CONTENT);

                        // 设置PopupWindow的显示位置和偏移量
                        if (position == clickedPosition) {
                            popupWindow.showAsDropDown(view, 0, 1);
                        }

                        //设置导出菜单项的点击事件
                        TextView exportItem = popupView.findViewById(R.id.export_item);
                        exportItem.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                popupWindow.dismiss();
                                if (!mUdiskRoot.exists() || !mUdiskRoot.isDirectory()) {
                                    Toast.makeText(SmartIntegrateTargetActivity.this, "未发现U盘,导出射靶成绩单失败", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                createExcel(mUdiskRoot);
                            }
                        });

                        // 设置删除菜单项的点击事件
                        TextView deleteItem = popupView.findViewById(R.id.delete_item);
                        deleteItem.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                popupWindow.dismiss();
                                Map<String, Object> record = (Map<String, Object>) getItem(position);
                                id = (int) record.get("id");

                                // 开始事务
                                db.beginTransaction();
                                try {
                                    String sql = "delete from record where id = ?";
                                    db.execSQL(sql, new String[]{String.valueOf(id)});

                                    sql = "delete from score where record_id = ?";
                                    db.execSQL(sql, new String[]{String.valueOf(id)});

                                    db.setTransactionSuccessful();
                                } catch (SQLException e) {
                                    e.printStackTrace();
                                } finally {
                                    db.endTransaction();
                                }

                                if (recordDataList.size() != 1) {
                                    if (position != recordDataList.size() - 1) {
                                        selectRecord(position + 1);
                                    } else {
                                        clickedPosition = position - 1;
                                        selectedItems.put(clickedPosition, true);
                                        selectRecord(position - 1);
                                    }
                                } else {
                                    recordScoreDataList.clear();
                                    recordScoreAdapter.notifyDataSetChanged();
                                    recordListChart.setData(10, new ArrayList<>());
                                    targetResultView.getTargetView(SmartIntegrateTargetActivity.this, recordScoreDataList, new HashMap<>(), recordTarget);
                                    sumView.setText("总发数 : ");
                                    missView.setText("脱靶 : ");
                                    highestView.setText("最高环数 : ");
                                    avgView.setText("平均环数 : ");
                                    varianceView.setText("方差 : ");
                                }
                                recordDataList.remove(position);
                                notifyDataSetChanged();
                            }
                        });
                        return true;
                    }
                });

                return view;

            }
        };

        //将recordAdapter设置到recordList
        recordList.setAdapter(recordAdapter);

        //历史列表默认首行选中
        selectedItems.put(0, true);
        recordAdapter.notifyDataSetChanged();

        //加载首行历史数据的成绩列表
        selectRecord(0);

        //点击屏幕弹出框消失
        recordWhole.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 关闭PopupWindow
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
            }
        });

        //扫描u盘状态
        scanUdiskRootDir();

        IntentFilter filter = new android.content.IntentFilter();
        filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
        filter.addDataScheme("file");
        registerReceiver(mStorageReceiver, filter);

    }

    //加载首行历史数据的成绩列表
    @SuppressLint("Range")
    private void selectRecord(int position) {
        if (recordAdapter.getCount() != 0) {
            Map<String, Object> firstMap = (Map<String, Object>) recordAdapter.getItem(position);
            id = (int) firstMap.get("id");

            recordScoreDataList = new ArrayList<>();
            String sql = "select num,ring,distance,x,y,time from score where ring >= 5 and record_id = ?";
            String[] args = new String[]{String.valueOf(id)};
            Cursor cursor = db.rawQuery(sql, args);
            while (cursor.moveToNext()) {
                int num = cursor.getInt(cursor.getColumnIndex("num"));
                float ring = cursor.getFloat(cursor.getColumnIndex("ring"));
                String distance = cursor.getString(cursor.getColumnIndex("distance"));
                float x = cursor.getFloat(cursor.getColumnIndex("x"));
                float y = cursor.getFloat(cursor.getColumnIndex("y"));
                Float time = cursor.getFloat(cursor.getColumnIndex("time"));
                Map<String, Object> map = new HashMap<>();
                map.put("record_num", num);
                map.put("record_ring", ring);
                map.put("record_distance", distance);
                map.put("x", x);
                map.put("y", y);
                map.put("record_time", time);
                recordScoreDataList.add(map);
            }
            cursor.close();

            String[] sfrom = {"record_num", "record_ring", "record_distance", "record_time"};
            int[] sto = {R.id.record_num, R.id.record_ring, R.id.record_distance, R.id.record_time};

            //创建适配器把成绩数据装配给成绩列表
            recordScoreAdapter = new SimpleAdapter(this, recordScoreDataList, R.layout.record_score_list_item, sfrom, sto) {
                // 初始时没有选中的行
                int selectedPosition = 0;

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    View view = super.getView(position, convertView, parent);

                    //默认首行选中并设置行的背景颜色
                    if (selectedPosition == position) {
                        //选中行背景颜色为绿色
                        view.setBackgroundColor(Color.parseColor("#0e932e"));
                    } else {
                        //其他为默认色
                        view.setBackgroundColor(Color.BLACK);
                    }

                    view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //点击行设置选中
                            selectedPosition = position;
                            notifyDataSetChanged();

                            //靶高亮显示该成绩
                            Map<String, Object> selectScoreMap = (Map<String, Object>) getItem(position);
                            targetResultView.getTargetView(SmartIntegrateTargetActivity.this, recordScoreDataList, selectScoreMap, recordTarget);
                        }
                    });

                    return view;

                }
            };

            //将recordScoreAdapter设置到recordScoreList
            recordScoreList.setAdapter(recordScoreAdapter);


            //胸环靶
            Map<String, Object> firstScoreMap = (Map<String, Object>) recordScoreAdapter.getItem(0);
            targetResultView.getTargetView(this, recordScoreDataList, firstScoreMap, recordTarget);

            //坐标系
            List<Score> coordList = new ArrayList<>();
            Score score = null;
            sql = "select num,ring,distance,x,y,time from score where record_id = ?";
            args = new String[]{String.valueOf(id)};
            cursor = db.rawQuery(sql, args);
            while (cursor.moveToNext()) {
                int num = cursor.getInt(cursor.getColumnIndex("num"));
                float ring = cursor.getFloat(cursor.getColumnIndex("ring"));
                score = new Score(num, ring, null, null, 0, 0, 0);
                coordList.add(score);
            }
            cursor.close();

            recordListChart.setData(coordList.size(), coordList);


            //枪型和计算数据
            String gunType = (String) firstMap.get("gunType");
            String sum = "总发数 : " + (int) firstMap.get("sum");
            String miss = "脱靶 : " + (int) firstMap.get("miss");
            String highest = "最高环数 : " + (float) firstMap.get("highest");
            String avg = "平均环数 : " + (float) firstMap.get("avg");
            String variance = "方差 : " + (float) firstMap.get("variance");

            if (gunType.equals("95式自动步枪")) {
                gunTypePic.setImageResource(R.drawable.rifle);
            } else {
                gunTypePic.setImageResource(R.drawable.pistol);
            }
            gunTypeView.setText(gunType + " 胸环靶");
            sumView.setText(sum);
            missView.setText(miss);
            highestView.setText(highest);
            avgView.setText(avg);
            varianceView.setText(variance);
        }

    }

    //u盘状态监听广播
    private android.content.BroadcastReceiver mStorageReceiver = new android.content.BroadcastReceiver() {
        @Override
        public void onReceive(android.content.Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_MEDIA_MOUNTED) ||
                    action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) {
                scanUdiskRootDir();
            }
        }
    };

    //u盘状态
    private void scanUdiskRootDir() {
        if (mUdiskRoot.exists() && mUdiskRoot.isDirectory()) {
            udisk.setVisibility(View.VISIBLE);
        } else {
            udisk.setVisibility(View.GONE);
        }
    }

    //导出射靶历史记录excel
    @SuppressLint("Range")
    private void createExcel(File mUdiskRoot) {
        String sql = "select a.shooter,a.gun_type,a.create_time,b.num,b.ring,b.distance,b.time,a.sum,a.miss,a.highest," +
                "a.avg,a.variance from record a inner join score b on a.id = b.record_id AND b.ring >= 5 where b.record_id = ?";
        Cursor cursor = db.rawQuery(sql, new String[]{String.valueOf(id)});
        List<ShotExcelData> shotExcelDataList = new ArrayList<>();
        ShotExcelData shotExcelData;
        while (cursor.moveToNext()) {
            String shooter = cursor.getString(cursor.getColumnIndex("shooter"));
            String gunType = cursor.getString(cursor.getColumnIndex("gun_type"));
            String createTime = cursor.getString(cursor.getColumnIndex("create_time"));
            int num = cursor.getInt(cursor.getColumnIndex("num"));
            float ring = cursor.getFloat(cursor.getColumnIndex("ring"));
            String distance = cursor.getString(cursor.getColumnIndex("distance"));
            float time = cursor.getFloat(cursor.getColumnIndex("time"));
            int sum = cursor.getInt(cursor.getColumnIndex("sum"));
            int miss = cursor.getInt(cursor.getColumnIndex("miss"));
            float highest = cursor.getFloat(cursor.getColumnIndex("highest"));
            float avg = cursor.getFloat(cursor.getColumnIndex("avg"));
            float variance = cursor.getFloat(cursor.getColumnIndex("variance"));
            shotExcelData = new ShotExcelData(shooter, gunType, createTime, num, ring, distance, time, sum, miss, highest, avg, variance);
            shotExcelDataList.add(shotExcelData);
        }

        try {
            String currData = DateUtil.format(DateUtil.date(), "yyyy年MM月dd日HH时mm分ss秒");
            String fileName = "射靶成绩单 " + currData + ".xls";
            File excel = new File(mUdiskRoot, fileName);

            WritableWorkbook workbook = Workbook.createWorkbook(new FileOutputStream(excel));
            WritableSheet sheet = workbook.createSheet("射靶成绩单", 0);

            // 写入标题
            Label title = new Label(0, 0, "射手");
            sheet.addCell(title);
            title = new Label(1, 0, "枪型");
            sheet.addCell(title);
            title = new Label(2, 0, "发序");
            sheet.addCell(title);
            title = new Label(3, 0, "环数");
            sheet.addCell(title);
            title = new Label(4, 0, "距离(米)");
            sheet.addCell(title);
            title = new Label(5, 0, "用时(秒)");
            sheet.addCell(title);
            title = new Label(6, 0, "总发数");
            sheet.addCell(title);
            title = new Label(7, 0, "脱靶");
            sheet.addCell(title);
            title = new Label(8, 0, "最高环数");
            sheet.addCell(title);
            title = new Label(9, 0, "平均环数");
            sheet.addCell(title);
            title = new Label(10, 0, "方差");
            sheet.addCell(title);
            title = new Label(11, 0, "取得时间");
            sheet.addCell(title);

            int r;
            Label data;
            int size = shotExcelDataList.size();
            // 写入数据
            for (int i = 0; i < size; i++) {
                shotExcelData = shotExcelDataList.get(i);
                r = i + 1;
                data = new Label(0, r, shotExcelData.getShooter());
                sheet.addCell(data);
                data = new Label(1, r, shotExcelData.getGunType());
                sheet.addCell(data);
                data = new Label(2, r, String.valueOf(shotExcelData.getNum()));
                sheet.addCell(data);
                data = new Label(3, r, String.valueOf(shotExcelData.getRing()));
                sheet.addCell(data);
                data = new Label(4, r, shotExcelData.getDistance());
                sheet.addCell(data);
                data = new Label(5, r, String.valueOf(shotExcelData.getTime()));
                sheet.addCell(data);
                data = new Label(6, r, String.valueOf(shotExcelData.getSum()));
                sheet.addCell(data);
                data = new Label(7, r, String.valueOf(shotExcelData.getMiss()));
                sheet.addCell(data);
                data = new Label(8, r, String.valueOf(shotExcelData.getHighest()));
                sheet.addCell(data);
                data = new Label(9, r, String.valueOf(shotExcelData.getAvg()));
                sheet.addCell(data);
                data = new Label(10, r, String.valueOf(shotExcelData.getVariance()));
                sheet.addCell(data);
                data = new Label(11, r, shotExcelData.getCreateTime());
                sheet.addCell(data);
            }

            workbook.write();
            workbook.close();

            //弹出导出excel消息提示
            for (int i = 0; i < 3; i++) {
                if (i != 0){
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(SmartIntegrateTargetActivity.this, "射靶成绩单导出中", Toast.LENGTH_LONG).show(); // 可以选择Toast.LENGTH_SHORT或Toast.LENGTH_LONG
                        }
                    }, 0);
                }
                else {
                    Toast.makeText(SmartIntegrateTargetActivity.this, "射靶成绩单导出中", Toast.LENGTH_LONG).show(); // 可以选择Toast.LENGTH_SHORT或Toast.LENGTH_LONG
                }
            }

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(SmartIntegrateTargetActivity.this, "射靶成绩单导出成功", Toast.LENGTH_SHORT).show();
                }
            }, 10000); // 延迟10秒

        } catch (IOException | WriteException e) {
            e.printStackTrace();
            Toast.makeText(this, "射靶成绩单导出失败", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        db.close();
    }
}